package cn.leida.ruoyi.framework.web.service;

import cn.hutool.core.util.NumberUtil;
import cn.leida.ruoyi.common.constant.CacheConstants;
import cn.leida.ruoyi.common.core.cache.ICacheService;
import cn.leida.ruoyi.common.core.domain.entity.SysUser;
import cn.leida.ruoyi.common.exception.user.UserPasswordNotMatchException;
import cn.leida.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException;
import cn.leida.ruoyi.common.utils.SecurityUtils;
import cn.leida.ruoyi.framework.security.context.AuthenticationContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录密码方法
 *
 * @author ruoyi
 */
@Component
public class SysPasswordService {
    @Autowired
    private ICacheService cacheService;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;


    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        Integer retryCount = 0 ;
        String cacheCountStr = cacheService.getCacheObject(CacheConstants.PWD_ERR_CNT_KEY, username) +"";
        if (NumberUtil.isInteger(cacheCountStr)) {
            retryCount = NumberUtil.parseInt(cacheCountStr);
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            cacheService.setCacheObject(CacheConstants.PWD_ERR_CNT_KEY, username, retryCount);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(SysUser user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        cacheService.deleteObject(CacheConstants.PWD_ERR_CNT_KEY, loginName);
    }

}
